package com.shiwaixiangcun.customer.module.intelligent

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.view.View
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CameraToken
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.module.intelligent.camerautil.Business
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_validate_network.*
import kotlinx.android.synthetic.main.top_bar_white.*


/**
 * 摄像头配置
 *
 * Wifi设置页面
 */
class ValidateNetworkActivity : BaseActivity(), ActivityCompat.OnRequestPermissionsResultCallback {

    /**
     * 摄像头设备名称
     */
    private var mCameraName: String = ""
    /**
     *摄像头设备ID
     */
    private var mCameraRC: String = ""
    private var mCameraDID: String = ""
    private var mWifiSsid: String = ""
    private var mWifiBssid: String = ""
    private var mWifiInfo: WifiInfo? = null
    private var mWifiManager: WifiManager? = null

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_validate_network)

        getIntentData()
        initWIFI()
        initViewAndEvent()

    }

    /**
     * 获取传递过来的数据
     */
    private fun getIntentData() {
        this.mCameraDID = intent.getStringExtra("camera_id")
        this.mCameraName = intent.getStringExtra("camera_name")
        this.mCameraRC = intent.getStringExtra("camera_rc")



        Business.getInstance().init(GlobalConfig.LechangeAppId, GlobalConfig.LechangeAppSecret, "openapi.lechange.cn:443")

        initCameraToken()

    }

    private fun initCameraToken() {
        val strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.get<String>(GlobalApi.cameraToken)
                .params("access_token", strToken)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<CameraToken>>() {}.type
                        val fromJson = JsonUtil.fromJson<DeviceBaseEntity<CameraToken>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                Business.getInstance().token = fromJson.data.verificationCamera
                            }
                        }
                    }

                })
    }


    /**
     * 获取wifi加密信息
     */
    private fun getWifiCapabilities(ssid: String): String? {
        var mCapabilities: String? = null
        var mScanResult: ScanResult? = null

        if (mWifiManager != null) {
            val mWifi = mWifiManager?.connectionInfo
            if (mWifi != null) {
                // 判断SSID是否�?��
                if (mWifi.ssid != null && (mWifi.ssid.replace(oldValue = "\"", newValue = "") == ssid)) {
                    val mList = mWifiManager?.scanResults
                    if (mList != null) {
                        for (s in mList) {
                            if (s.SSID.replace("\"".toRegex(), "") == ssid) {
                                mScanResult = s
                                break
                            }
                        }
                    }
                }
            }
        }
        mCapabilities = if (mScanResult != null) mScanResult.capabilities else null
        return mCapabilities
    }


    /**
     * 获取Wifi 信息  并对Wifi进行验证
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("WifiManagerLeak", "SetTextI18n")
    private fun initWIFI() {
        mWifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
        mWifiInfo = mWifiManager?.connectionInfo
        mWifiSsid = mWifiInfo?.ssid!!
        mWifiBssid = mWifiInfo?.bssid!!



        when {

            is24GHz(mWifiInfo!!.frequency) -> {
                setViewVisible(false)
                iv_wifi_status.setImageResource(R.drawable.wifi_connect)
                tv_info_connect.text = mWifiSsid.dropLast(1).reversed().dropLast(1).reversed()
                btn_add_device.visibility = View.VISIBLE
                btn_add_device.setOnClickListener {
                    Log.e(BUG_TAG, "click")
                    if (edt_password.text.toString().isEmpty()) {
                        showToastShort("请输入当前连接Wifi的密码")
                    } else {
                        val bundle = Bundle()
                        bundle.putString("camera_id", mCameraDID)
                        bundle.putString("camera_name", mCameraName)
                        bundle.putString("wifi_name", tv_info_connect.text.toString())
                        bundle.putString("wifi_pwd", edt_password.text.toString())
                        bundle.putString("camera_rc", mCameraRC)
                        readyGoThenKill(CameraStartActivity::class.java, bundle)
                    }

                }

            }
            is5GHz(mWifiInfo!!.frequency) -> {
                setViewVisible(true)
                iv_wifi_status.setImageResource(R.drawable.wifi_connect)

                tv_info_connect.text = "智能摄像头暂不支持5G网络"
                btn_add_device.visibility = View.GONE
                tv_change_network.visibility = View.VISIBLE
                tv_change_network.setOnClickListener {
                    val wifiSettingsIntent = Intent("android.settings.WIFI_SETTINGS")
                    startActivity(wifiSettingsIntent)
                }
            }
            else -> {
                iv_wifi_status.setImageResource(R.drawable.wifi_unconnect)
                tv_info_connect.text = "你的手机未连接Wifi"
                tv_desc_wifi.text = "配置智能摄像机需要连接无线WIFI"
                setViewVisible(true)
                btn_add_device.visibility = View.GONE
                tv_change_network.text = "设置无线网络"
                tv_change_network.visibility = View.VISIBLE
                tv_change_network.setOnClickListener {
                    val wifiSettingsIntent = Intent("android.settings.WIFI_SETTINGS")
                    startActivity(wifiSettingsIntent)
                }

            }
        }


    }

    /**
     * 判断wifi是否为2.4G
     * @param freq
     * @return
     */
    private fun is24GHz(freq: Int): Boolean {
        return freq in 2401..2499
    }

    /**
     * 判断wifi是否为5G
     * @param freq
     * @return
     */
    private fun is5GHz(freq: Int): Boolean {
        return freq in 4901..5899
    }


    /**
     * Wifi未连接时候显示的内容
     */
    private fun setViewVisible(unConnect: Boolean) {
        if (unConnect) {
            edt_password.visibility = View.GONE
            tv_desc_wifi.visibility = View.VISIBLE

            view_divider.visibility = View.GONE
        } else {
            edt_password.visibility = View.VISIBLE
            tv_desc_wifi.visibility = View.GONE
            btn_add_device.visibility = View.VISIBLE
            view_divider.visibility = View.VISIBLE

        }


    }


    private fun initViewAndEvent() {
        back_left.setOnClickListener { finish() }
        tv_page_name.text = "连接无线网络"

    }


}
